package com.ruoyi.yuwen.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;

import com.github.kevinsawicki.http.HttpRequest;
import com.google.gson.Gson;
import com.ruoyi.common.newAdd.returnResult.Data;
import com.ruoyi.common.newAdd.returnResult.Res;
import com.ruoyi.common.newAdd.utils.Api;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.yuwen.domain.WeixinUser;
import com.ruoyi.yuwen.service.IWeixinUserService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 微信用户Controller
 * 
 * @author ruoyi
 * @date 2023-02-27
 */
@RestController
@RequestMapping("/yuwen/weixinuser")
public class WeixinUserController extends BaseController
{
    @Autowired
    private IWeixinUserService weixinUserService;

    /**
     * 小程序appId
     */
    String appid = "wx24cbb9b24b2b3b22";
    /**
     * 小程序 appSecret
     */
    String secret = "0db5dfd2dc971156552f4686ff8711eb";

    /**
     * 查询微信用户列表
     */
    @PreAuthorize("@ss.hasPermi('yuwen:user:list')")
    @GetMapping("/list")
    public TableDataInfo list(WeixinUser weixinUser)
    {
        startPage();
        List<WeixinUser> list = weixinUserService.selectWeixinUserList(weixinUser);
        return getDataTable(list);
    }

    /**
     * 导出微信用户列表
     */
    @PreAuthorize("@ss.hasPermi('yuwen:user:export')")
    @Log(title = "微信用户", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, WeixinUser weixinUser)
    {
        List<WeixinUser> list = weixinUserService.selectWeixinUserList(weixinUser);
        ExcelUtil<WeixinUser> util = new ExcelUtil<WeixinUser>(WeixinUser.class);
        util.exportExcel(response, list, "微信用户数据");
    }

    /**
     * 获取微信用户详细信息
     */
    @PreAuthorize("@ss.hasPermi('yuwen:user:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(weixinUserService.selectWeixinUserById(id));
    }

    /**
     * 新增微信用户
     */
    @PreAuthorize("@ss.hasPermi('yuwen:user:add')")
    @Log(title = "微信用户", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    public AjaxResult add(@RequestBody WeixinUser weixinUser)
    {
        return toAjax(weixinUserService.insertWeixinUser(weixinUser));
    }

    /**
     * 修改微信用户
     */
    @PreAuthorize("@ss.hasPermi('yuwen:user:edit')")
    @Log(title = "微信用户", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody WeixinUser weixinUser)
    {
        return toAjax(weixinUserService.updateWeixinUser(weixinUser));
    }

    /**
     * 删除微信用户
     */
    @PreAuthorize("@ss.hasPermi('yuwen:user:remove')")
    @Log(title = "微信用户", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(weixinUserService.deleteWeixinUserByIds(ids));
    }


    /**
     * @api {GET} /user/WXlogin 微信登录
     * @apiGroup user
     * @apiParam {String} [jscode] 微信jscode
     * @apiSuccess {String} [openId] 微信用户openId
     * @apiSuccess {String} [token] 用户token
     */
    @GetMapping("/WXlogin")
    public Res WXlogin(@RequestParam("jscode") String jscode) {
        //获取用户openid
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + appid + "&secret=" + secret +
                "&js_code=" + jscode + "&grant_type=authorization_code";
        HttpRequest request = Api.getEE(url);
        String body = request.body();
        System.out.println("body");
        System.out.println(body);
        Gson gson = new Gson();
        Map<String, Object> map = new HashMap<String, Object>();
        map = gson.fromJson(body, map.getClass());
        String openId;
        String sessionkey;
        if (map.containsKey("openid")) {
            openId = map.get("openid").toString();
            sessionkey = map.get("session_key").toString();
        } else {
            return Res.error("登录异常，请重新登录！");
        }
        WeixinUser weixinUser = new WeixinUser();
        weixinUser.setOpenId(openId);
        List<WeixinUser> userList = weixinUserService.selectWeixinUserList(weixinUser);
        if (userList.size() > 0) {
            weixinUser = userList.get(0);
        } else {
            weixinUserService.insertWeixinUser(weixinUser);
        }

        return Res.ok().put("data", Data.ok().put("openId", openId).put("sessionkey",sessionkey));
    }
}
